package com.smart.car.message.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.smart.car.common.res.utils.SampleByTxUtil;
import com.smart.car.message.entity.MessageInfo;
import com.smart.car.message.entity.MessageInfoExample;
import com.smart.car.message.mapper.MessageInfoMapper;
import com.smart.car.message.service.MessageInfoService;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class MessageInfoServiceImpl implements MessageInfoService {

	@Autowired
	private MessageInfoMapper messageMapper;

	@Override
	public List<MessageInfo> list() {
		MessageInfoExample example = new MessageInfoExample();
		List<MessageInfo> infoList = messageMapper.selectByExample(example);
		return infoList;
	}

	//记录发送的通知消息
	@Override
	public int sendNotice(String json) {
		log.info("message数据是 = " + json);
		MessageInfo message = JSONObject.parseObject(json, MessageInfo.class);
		int i = messageMapper.insertSelective(message);
		return i;
	}


	@Value("${tengxun.sms.secretId}")
	private String secretId;
	@Value("${tengxun.sms.secretKey}")
	private String secretKey;
	@Value("${tengxun.sms.sdkAppid}")
	private String sdkAppid;
	@Value("${tengxun.sms.sign}")
	private String sign;
	@Value("${tengxun.sms.templateId}")
	private String templateId;

	/**
	 * 腾讯云发送短信v3.0
	 * 注意：由于阿里云和腾讯云有些对象名称是一致的，为了防止导错包，附带了整体路径
	 */
	@Override
	public boolean sendSmsByTx(String phoneNum, String code, Long eTime) {
		try {
			//创建客户端
			SmsClient client = SampleByTxUtil.createClient(secretId, secretKey);
			com.tencentcloudapi.sms.v20190711.models.SendSmsRequest req = new com.tencentcloudapi.sms.v20190711.models.SendSmsRequest();

			//下发手机号码，必须采用 E.164 标准，格式为+[国家或地区码][手机号]，单次请求最多支持200个手机号。可以在前端拼接区号。
			//填写手机号：String[] phoneNumbers = {"+86182666666666"};
			String[] phoneNumbers = new String[]{"+86"+phoneNum}  ;
			//我们只是演示的一个手机号，若是批量，则可以采用循环放入
			//System.out.println(Arrays.toString(phoneNumbers));

			//配置参数
			req.setPhoneNumberSet(phoneNumbers);
			req.setSmsSdkAppid(sdkAppid);
			req.setSign(sign);
			req.setTemplateID(templateId);

			/* 模板参数: 若无模板参数，则设置为空。我们的模板填了{1}{2}，分别是验证码和redis有效期 */
			String[] templateParamSet = {code, eTime.toString()};
			req.setTemplateParamSet(templateParamSet);

			//请求发送短信
			com.tencentcloudapi.sms.v20190711.models.SendSmsResponse resp = client.SendSms(req);
			log.info("打印结果：>>"+com.tencentcloudapi.sms.v20190711.models.SendSmsResponse.toJsonString(resp));
			if (resp != null) {
				return true;
			}
		} catch (TencentCloudSDKException e) {
			log.error("短信发送失败:{},",e.toString());
		}
		return false;
	}

}
